SpringBoot Cache 的使用
什么是 Spring Cache
Spring Cache 本身是一个缓存体系的抽象实现,并没有具体的缓存能力,要使用 Spring Cache 还需要具体的缓存实现来完成。
Spring Boot 集成了多种 cache 的实现,如果你没有在配置类中声明 CacheManager,那么 SpringBoot 会按顺序在下面的实现类中寻找:
- Generic
- JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
- EhCache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
不过注意,如果使用的是 Redis 不需要使用这个 spring-boot-starter-cache 它被内置到 spring-boot-starter-data-redis 这个包里面去了
如果什么都没有配置默认使用的是 Simple 即,使用 ConcurrentHashMap 来作为存储缓存
官方查询图书的案例
配置环境
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>